#define _CRT_SECURE_NO_WARNINGS 1

class Solution
{
    int m, n;
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    vector<vector<bool>> vis;
public:
    int numIslands(vector<vector<char>>& grid)
    {
        m = grid.size();
        n = grid[0].size();
        int ret = 0;
        vis = vector<vector<bool>>(m, vector<bool>(n));

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == '1' && !vis[i][j])
                {
                    vis[i][j] = true;
                    dfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }
    void dfs(vector<vector<char>>& grid, int a, int b)
    {
        for (int i = 0; i < 4; i++)
        {
            int x = a + dx[i];
            int y = b + dy[i];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == '1')
            {
                vis[x][y] = true;
                dfs(grid, x, y);
            }
        }
    }
};

class Solution
{
    vector<vector<bool>> vis;
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    int m, n;
public:
    int numIslands(vector<vector<char>>& grid)
    {
        m = grid.size(), n = grid[0].size();
        vis = vector<vector<bool>>(m, vector<bool>(n));
        int ret = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (!vis[i][j] && grid[i][j] == '1')
                {
                    bfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }
    void bfs(vector<vector<char>>& grid, int a, int b)
    {
        queue<pair<int, int>> q;
        q.push({ a, b });
        vis[a][b] = true;
        while (q.size())
        {
            auto [_x, _y] = q.front();
            q.pop();
            for (int i = 0; i < 4; i++)
            {
                int x = _x + dx[i];
                int y = _y + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == '1')
                {
                    q.push({ x, y });
                    vis[x][y] = true;
                }
            }
        }
    }
};

